from urllib.parse import urlencode, parse_qs
from urllib.request import urlopen
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from django.conf import settings
import json

from .exceptions import QQAPIError, QQAPIException
from . import constants

import logging

logger = logging.getLogger('django')


class OAuthQQ(object):
    """
    QQ认证辅助工具类
    """
    def __init__(self, client_id=None, client_secret=None, redirect_uri=None, state=None):
        self.client_id = client_id or settings.QQ_CLIENT_ID
        self.client_secret = client_secret or settings.QQ_CLIENT_SECRET
        self.redirect_uri = redirect_uri or settings.QQ_REDIRECT_URI
        self.state = state or settings.QQ_STATE  # 用于保存登录成功后的跳转页面路径

    def get_qq_login_url(self):
        """
        获取qq登录的网址
        :return: url网址
        """
        params = {
            'response_type': 'code',  # 获取code
            'client_id': self.client_id,  # 应用的id
            'redirect_uri': self.redirect_uri,  # 扫码后回调的页面
            'state': self.state,  # QQ登陆成功后跳转的页面
            'scope': 'get_user_info',  # 表示扫码是为了获取用户的信息client_id
        }
        # 准备url
        login_url = 'https://graph.qq.com/oauth2.0/authorize?' + urlencode(params)
        return login_url

    def get_access_token(self, code):
        """
        获取access_token
        :param code: qq提供的code
        :return: access_token
        """
        params = {
            'grant_type': 'authorization_code',
            'client_id': self.client_id,
            'client_secret': self.client_secret,
            'code': code,
            'redirect_uri': self.redirect_uri
        }
        # 准备url,　拼接地址
        url = 'https://graph.qq.com/oauth2.0/token?' + urlencode(params)

        # # 使用code向ＱＱ服务器发送请求，获取access_token
        # response = urlopen(url)
        #
        # # 获取响应
        # response_data = response.read().decode()
        #
        # # 转成响应字典
        # response_dict = parse_qs(response_data)
        #
        # # 获取access_token：被存放在字典中，只有access_token一个元素，　所以返回数据的时候取[0]
        # access_token = response_dict.get('access_token', None)
        #
        # # 如果没有获取到的话抛出异常
        # if not access_token:
        #     logger.error('code=%s msg=%s' % (response_dict.get('code'), response_dict.get('msg')))
        #     raise QQAPIError('获取access_token失败')
        #
        # return access_token[0]
        try:
            # 使用code向ＱＱ服务器发送请求，获取access_token
            response = urlopen(url)
            print(response)
            # 获取响应
            response_data = response.read().decode()

            # 转成响应字典
            response_dict = parse_qs(response_data)

            # 获取access_token：被存放在字典中，只有access_token一个元素，　所以返回数据的时候取[0]
            access_token = response_dict.get('access_token')[0]

        # 如果没有获取到的话抛出异常
        except Exception as e:
            logger.error(e)
            raise QQAPIException('获取access_token失败')

        return access_token

    def get_openid(self, access_token):
        """
        获取用户的openid
        :param access_token:qq提供的access_token
        :return: open_id:是我们，用户在注册个人qq账号时qq服务器给分配的用户的唯一标识
        """
        # 准备url
        url = 'https://graph.qq.com/oauth2.0/me?access_token=' + access_token

        # 美多向ＱＱ服务器发送请求获取openid
        response_str = ''
        try:
            response = urlopen(url)
            response_str = response.read().decode()
            # print("--------------------------%s" % response_str)

            # 返回数据callback
            response_dict = json.loads(response_str[10:-4])
            # print(response_str[10:-4])
            # print(response_str[0:-4])

            # 获取open_id
            openid = response_dict.get('openid')

        except Exception:
            data = parse_qs(response_str)
            logger.error('code=%s msg=%s' % (data.get('code'), data.get('msg')))
            raise QQAPIError

        return openid

    @staticmethod
    def check_save_user_token(token):
        """
        检验保存用户的数据
        :param token: token
        :return: openid or None
        """
        serilizer = Serializer(settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)

        try:
            data = serilizer.loads(token)
        except BadData:
            return None
        else:
            return data.get('openid')

    @staticmethod
    def generate_save_user_token(openid):
        """
        生成保存用户数据的token
        :param openid: 用户的openid
        :return: token
        """
        serializer = Serializer(settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)
        data = {'openid': openid}
        token = serializer.dumps(data).decode()

        return token











